import unittest
import os
import sys
import time


# 添加项目根目录到Python路径
root_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.append(root_dir)

# 测试报告保存目录
report_dir = os.path.join(root_dir, 'tests', 'reports')
if not os.path.exists(report_dir):
    os.makedirs(report_dir)

def run_all_tests():
    """
    发现并运行tests目录下的所有测试，生成HTML测试报告
    """
    # 获取tests目录
    tests_dir = os.path.join(root_dir, 'tests')
    
    # 发现所有测试用例
    loader = unittest.TestLoader()
    suite = loader.discover(tests_dir, pattern='test_*.py')
    
    # 生成报告文件名（包含时间戳）
    timestamp = time.strftime('%Y%m%d_%H%M%S')
    report_file = f'test_report_{timestamp}'
    
    
    # 运行测试并生成文本报告
    start_time = time.time()
    with open(os.path.join(report_dir, f'{report_file}.txt'), 'w', encoding='utf-8') as f:
        runner = unittest.TextTestRunner(stream=f, verbosity=2)
        result = runner.run(suite)
    end_time = time.time()

    # 生成统计信息
    duration = end_time - start_time
    stats = f'''
测试概要
========
执行时间: {duration:.2f}秒
用例总数: {result.testsRun}
成功用例: {result.testsRun - len(result.failures) - len(result.errors) - len(result.skipped)}
失败用例: {len(result.failures)}
错误用例: {len(result.errors)}
跳过用例: {len(result.skipped)}

失败详情:
'''
    
    # 添加失败/错误详细信息
    for i, (test, traceback) in enumerate(result.failures + result.errors, 1):
        stats += f'{i}. {test.id()}\n{traceback}\n\n'
    
    # 写入统计信息到文件
    with open(os.path.join(report_dir, f'{report_file}.txt'), 'a', encoding='utf-8') as f:
        f.write(stats)

    
    # 打印测试结果摘要
    print(f"\n测试完成！")
    print(f"运行测试: {result.testsRun}")
    print(f"成功: {result.testsRun - len(result.failures) - len(result.errors) - len(result.skipped)}")
    print(f"失败: {len(result.failures)}")
    print(f"错误: {len(result.errors)}")
    print(f"跳过: {len(result.skipped)}")
    print(f"\n测试报告已保存到: {os.path.join(report_dir, report_file + '.txt')}")
    
    return result

if __name__ == '__main__':
    run_all_tests()